package com.tongtech.proxy.core.acl;

import com.tongtech.proxy.core.utils.ProxyConfig;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

public class Authenticate {

    // 尝试进行身份验证
    private static boolean authenticate(String username, String password) {
        try {
            // 构建POST请求
            URL url = new URL(ProxyConfig.LOGIN_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);

            // 提交用户名和密码
            String credentials = "username=" + username + "&password=" + password;
            connection.getOutputStream().write(credentials.getBytes());

            // 获取响应
            int responseCode = connection.getResponseCode();

            // 如果响应码为200，表示身份验证成功
            return responseCode == 200;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 获取flag
    private static String getFlag() {
        try {
            // 构建GET请求
            URL url = new URL(ProxyConfig.LOGIN_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 获取flag
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String flag = reader.readLine();
            reader.close();

            return flag;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
